const host = "http://local.da.com/api/";

export default class Https{
    //刷新token
     autoLogin(){
        return new Promise((resolve,reject)=>{
          wx.request({
            url: host+'wx/refresh',
            data:{uid:wx.getStorageSync('userInfo').id},
            method:"post",
            success(res){
              console.log(res.data)
              wx.setStorageSync('token', res.data.data)
              resolve(res)
            }
          })
        })
      }
      
    request(url,data,method){
   
        
      return new Promise((resolve,reject)=>{
           //获取token过期时间
      var expire = wx.getStorageSync('token').expire
      //当前时间戳
        var timestamp = new Date().getTime() 
        var time = timestamp / 1000
      // 如果过期时间  小于 当前时间 加 10 秒 则证明此token 已过期 准备提前刷新
         if( expire <=  time  ){
         //调用刷新token接口 那时旧的token 还有效
            this.autoLogin().then(()=>{
                this.request(url, data, method).then(res=>{
                  resolve(res)
                });
            })
         }   
         
         var header = {
          'content-type': 'application/json',
          'token':wx.getStorageSync('token').token
        }

        wx.request({
          url: host+url,
          data: data || {},
          method: method ||'GET',
          header:header,
          success: (result) => {
             var statusCode = result.statusCode
             if(statusCode !== 200){
               wx.showToast({
                 title: '网络异常，请重试',
                 icon:"none",
                 duration:3000
               })
             }
             resolve(result.data)
          },
          fail: (res) => {
            wx.showToast({
              title: '网络异常，请重试',
              icon:"none"
            })
            reject(res)
          }
          
        })
      })
    
    }

}

